//package com.ly.mpayment.rest.system.slow;
//
//import com.alibaba.fastjson.JSON;
//import com.alibaba.fastjson.JSONObject;
//import com.ly.mpayment.core.util.DateUtils;
//import com.ly.mpayment.core.util.StringUtils;
//import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
//import com.wechat.pay.contrib.apache.httpclient.auth.AutoUpdateCertificatesVerifier;
//import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner;
//import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials;
//import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Validator;
//import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
//import com.wechat.pay.contrib.apache.httpclient.util.RsaCryptoUtil;
//import org.apache.http.client.HttpClient;
//import org.apache.http.client.methods.CloseableHttpResponse;
//import org.apache.http.client.methods.HttpGet;
//import org.apache.http.client.utils.URIBuilder;
//import org.apache.http.util.EntityUtils;
//import org.apache.log4j.Logger;
//import org.springframework.stereotype.Component;
//
//import javax.crypto.BadPaddingException;
//import javax.servlet.http.HttpServletRequest;
//import javax.ws.rs.POST;
//import javax.ws.rs.Path;
//import javax.ws.rs.core.Context;
//import java.io.*;
//import java.net.URI;
//import java.net.URISyntaxException;
//import java.security.*;
//import java.security.cert.*;
//import java.security.cert.Certificate;
//import java.security.spec.InvalidKeySpecException;
//import java.security.spec.PKCS8EncodedKeySpec;
//import java.util.Base64;
//import java.util.Random;
//
//@Component
//@Path("system/wechat")
//public class WechatRest {
//    Logger logger = Logger.getLogger(WechatRest.class);
//    /**
//     * 微信回调
//     * {
//     *     "id": "EV-2018022511223320873",
//     *     "create_time": "2015-05-20T13:29:35+08:00",
//     *     "resource_type": "encrypt-resource",
//     *     "event_type": "TRANSACTION.SUCCESS",
//     *     "summary": "支付成功",
//     *     "resource": {
//     *         "original_type": "transaction",
//     *         "algorithm": "AEAD_AES_256_GCM",
//     *         "ciphertext": "",
//     *         "associated_data": "",
//     *         "nonce": ""
//     *     }
//     * }
//     * @param data
//     * @param request
//     * @return
//     */
//    @POST
//    @Path("call_back")
//    public String callBack(String data,@Context HttpServletRequest request) {
//        String signature = request.getHeader("Wechatpay-Signature");
//        String timestamp = request.getHeader("Wechatpay-Timestamp");
//        String nonce = request.getHeader("Wechatpay-Nonce");
//        String serial = request.getHeader("Wechatpay-Serial");
//        String authorization = request.getHeader("Authorization");
//
//        logger.info("wechat_callBack:"+data+",sign:"+signature+",serial:"+serial+",nonce:"+nonce+",timestamp:"+timestamp+",authorization:"+authorization);
//        if(StringUtils.isBlank(data)){
//            return "0";
//        }
//
//        JSONObject wechat = JSONObject.parseObject(data);
//
//
//        JSONObject result = new JSONObject();
//        result.put("code","SUCCESS");
//        result.put("message","成功");
//        return result.toString();
//    }
//
//    /**
//     * 我方对响应验签，和应答签名做比较，使用微信平台证书.
//     *
//     * @param wechatpaySerial    response.headers['Wechatpay-Serial']    当前使用的微信平台证书序列号
//     * @param wechatpaySignature response.headers['Wechatpay-Signature']   微信平台签名
//     * @param wechatpayTimestamp response.headers['Wechatpay-Timestamp']  微信服务器的时间戳
//     * @param wechatpayNonce     response.headers['Wechatpay-Nonce']   微信服务器提供的随机串
//     * @param body               response.body 微信服务器的响应体
//     * @return the boolean
//     */
////    public boolean responseSignVerify(String wechatpaySerial, String wechatpaySignature, String wechatpayTimestamp, String wechatpayNonce, String body) {
////
////        if (CERTIFICATE_MAP.isEmpty() || !CERTIFICATE_MAP.containsKey(wechatpaySerial)) {
////            refreshCertificate();
////        }
////        Certificate certificate = CERTIFICATE_MAP.get(wechatpaySerial);
////
////        final String signatureStr = createSign(wechatpayTimestamp, wechatpayNonce, body);
////        Signature signer = Signature.getInstance("SHA256withRSA");
////        signer.initVerify(certificate);
////        signer.update(signatureStr.getBytes(StandardCharsets.UTF_8));
////
////        return signer.verify(Base64Utils.decodeFromString(wechatpaySignature));
////    }
//    //请求
//    HttpClient httpClient ;
//
//    private  String mchId = "1614745877";
//    private  String appid = "wx235da5587f90709a";
//    //回调通知地址
//    private  String notifyUrl = "https://wx.kkshs.com/mpayment/client/wechat/call_back";
//    //下单地址s
//    private String payJsapi = "https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi";
//    private String payH5 = "https://api.mch.weixin.qq.com/v3/pay/transactions/h5";
//
//
//
//    //商户key 秘钥
//    private  String privateKey = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC6AhvhGQ5rHiEC" +
//            "n6T7ZS2jWPgLknJ0ohKRBHpQTEa30jBOsrbnwCCzHAhIQdVQSykya1CmzfYuqrWq" +
//            "ZITr+GxT6Gc4j/xsL/wbCNCBN6XdByfz5f+jYPln47xhPz9A5eAc3U+iIpwZJCUT" +
//            "TiPH7SPB91qecG6Q/wsLPJTfpgOynD0NU0e2s8DkIj8321xx7Ru5Kxyb3Hx44NqJ" +
//            "fmrZTvXc1oEE6XDQ8nHULGr3wgph2CrdfSnDrFL6n6MUbVqqfcDjZ+GikJwPS7H6" +
//            "BMFgN6EbPkGt4tRDIQo0G6uipPFdSJfjjCYBhRSFmvarfn+uZ2nnOaF1fQH1FBOs" +
//            "uhaEtvh9AgMBAAECggEBAIhYWWVDv5znRd0tdnrMbIqrAY9B9uHll2RzetD3SHMg" +
//            "AEb/mzD/VTjVGIEWuK0VmwoZPdI3cPg+K9HNwt1RiN5soZUFfkszVUHf0S6Wwt7k" +
//            "ivWuJxf0Un1DoudJvCzvE7s0wlWftvp60y52faXj/u0ESomO8o0YVlkTPDE/+L/n" +
//            "pKLZi3OLBDRZc+F65AToP5+FXcFswfexSkIaHSGgmt8PZ8J+GSe5HYhSl5wLDxe2" +
//            "fGJs8u/YmNp8lhX/OHc/DG5bX6H4yKDRYkymNouGcTlhRkZWbS0pJUUV9O4rdLGQ" +
//            "avMCT/36fc0E+OobIljPaeMIDyXeqOMSeJXQM5E7m4UCgYEA3qoPGP84b6eiKb8g" +
//            "xH8exokurPyKQBC+4WrzbYV9BwpqcMeZ1sPGmrLJOOiG76iZeU33BYLwp0uVldYG" +
//            "xnSlrU7rhojTmrnd9bU01PFVocxsIWfHuRpNG9IWcpSRboQmDnuoI+99f9iMOE/D" +
//            "oOhW2lQDYZpqdygDo2geBPXBX9cCgYEA1dsm50EbJsc4sKL1Bf5Ta/sXJ3gASNIp" +
//            "msGtf7rBqSm7JZUrxXvZDul/CNzn0RE9WaSpkSAgnT3gItVxwFvPeilDDZq1aH6j" +
//            "RRyytB95swpGyP3+0oRG9JcG29mcMKzCe+p0hnvknO7ox7XWe5G61bPN7C4cKDHP" +
//            "/G9t6B+Er8sCgYBHMuG5AIMvUM8NwkvcCTnyChOexPIAIlqnAefs8W5VPgNjJLAQ" +
//            "eHGdLeYiCFh9cdABdeizHneNRyIB03o/IzWHAWFWl5HyO9S5qMPIA5N6NT+uPt0i" +
//            "V0KozrjW0qLeT+tLXkcZlo7uvnO33emUHjcHgS3Dm/jHOUhQjA5tT5gR6QKBgEKZ" +
//            "v6Hhes022gbYmSpGrEBCsFFQY/ZJzT8u9hODW/CM2IW50SntignE2hUuhttrXQnf" +
//            "6BcURFP0AyuWAZkAfrrywrkn5zslxT8u0tCZxNLnbmgGAigZnedqaW5qdOQLyX3B" +
//            "5IxFZUsidEhN7wAIwIDxQD4/lfFGohlhsn7J4g7FAoGBALflW3A/68EVkmEcB4WF" +
//            "i7L5zzUdgKtGDz3Z0iyr/78+fv/zuWy7zbU5oCPKfwjwa4jiKdwwGyAo98MQsNzr" +
//            "H1OKQXsWABQNdn+VvznAwOKH0ilymXOc8DJ3Jll2C+eDiXEYd9jJOJ1t87Ovb7AW" +
//            "IzSum5w+R3TU+FiaFFszNueZ";
//    //证书编号
//    private  String mchSerialNo = "5B73B170A84F8917B1469BCC7771E7A8E441AA65";
//    private  String apiV3Key = "l6L9hHEPTaSa2hSA73Nj1G0GitQ3sm61";
//
//
//    /**
//     * 下单
//     * @param total
//     * @throws Exception
//     */
//    public JSONObject commitOrder(int total,String title) throws Exception {
//        JSONObject rootNode = new JSONObject();
//        rootNode.put("mchid",mchId);
//        rootNode.put("appid",appid);
//        rootNode.put("description",title);
//        rootNode.put("notify_url",notifyUrl);
//        rootNode.put("out_trade_no",wxOrderNo());
//        JSONObject amount = new JSONObject();
//        //单位分
//        amount.put("total",total);
//        amount.put("currency","CNY");
//        rootNode.put("amount",amount);
//        JSONObject scene_info = new JSONObject();
//        scene_info.put("payer_client_ip","127.0.0.1");
//        JSONObject h5_info = new JSONObject();
//        h5_info.put("type","Wap");
//        scene_info.put("h5_info",h5_info);
//        rootNode.put("scene_info",scene_info);
//
//        String authorization = getToken("POST",payH5,rootNode.toString());
//        logger.info("authorization:"+authorization+",data:"+rootNode.toString());
//        String bodyAsString = com.ly.mpayment.core.util.HttpClient.postWechat(payH5,rootNode.toString(),authorization);
//        rootNode.clear();
//        JSONObject  h5 = JSONObject.parseObject(bodyAsString);
//        System.out.println(bodyAsString);
//        if(h5.containsKey("h5_url")){
//            rootNode.put("h5_url",h5.getString("h5_url"));
//            return rootNode;
//        }
//        return null;
//    }
//
//    public static  void main(String[] args) throws Exception {
//        //new WechatRest().getWechat();
//        //testOrder();
//        new WechatRest().commitOrder(1,"移动");
//
//        //new WechatRest().rsaDecryptOAEP("YrkTv2zwcwz30IWdCveUM3G7/npfVKBI9o1+K/HLjUbiak+M1shVropGiHqFZt5z+nKS4O/sS/AF7BK/xmbQguSLI5Zi+zwPR5X2whECvxb4o0U6EnpEak+ttqNVzjBNnMFAcSzScsSw6as9mbBwvUtYXeOGhWz8QcfGVLjOGd/tlic5e4yF2Pyab9lK/tiwXSOPoISP0jkWDTCLCbmx/Rb/WMOUgEJFKv3WOjhUWLRPREQ73NYfrORsAY8iSrp5zExR0FKxYQKffBSDLjwNVVE2+gJvdomHiSq1plrrGtiAEppugZy8SAvKljICNPzb1NaPp4TOAf5i/hwiCoIRl/NMKnZVYIqtdMZNcPbozByqcwhTPndeF9dFfo7apnRfJVN1F65v7Hzr3PXK2TlYfJd87I61B2L1x23E2aQvdgVkR5r7dLk6SiRX1FfvcV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sEbGoSQZGMW52YS/UhV0ioJVngUHZKgwtkjUpJmHCU6HxAioxC7aOynk1hZTy85h9k0A/w5iNeK5cIuIkkSIWweS/nI1Wha/wjcRuiJx1L73VlecUGIHAWIKifhmpMN2uqSTNxQ5sxU1ZbB1dgKL4IM8x/JbKlhTnTSLDI/qek7KWV/ySVOYrTkahKpWGqTxkBaZub/bBe/tL99x3123XK6BaKoJgc8SgnmnZI+ycExibxlulmiVnKk3ekZEWzqKil0aRurOvPTNaFag3RmiMo2jyq0DgRNDLVDtbAkKumDOc2G0jhcJY4egz5cTchm2OdWEI/RsR8GM/sFCkm+aPGJuBW2x/Dbg==");
//        // 使用商户私钥解密
//
//    }
//
//
////    /**
////     * 加密
////     * @param text
////     */
////    public void encryptOAEP(String text){
////        // 建议从Verifier中获得微信支付平台证书，或使用预先下载到本地的平台证书文件中
////        X509Certificate wechatpayCertificate = verifier.getValidCertificate();
////        try {
////            String ciphertext = RsaCryptoUtil.encryptOAEP(text, wechatpayCertificate);
////        } catch (IllegalBlockSizeException e) {
////            e.printStackTrace();
////        }
////    }
//    /**
//     * 解密
//     * @param ciphertext
//     * @return
//     * @throws BadPaddingException
//     * @throws IOException
//     */
//    public String rsaDecryptOAEP(String ciphertext)
//            throws BadPaddingException, IOException {
//        // 加载商户私钥（privateKey：私钥字符串）
//        PrivateKey merchantPrivateKey = PemUtil
//                .loadPrivateKey(new ByteArrayInputStream(privateKey.getBytes("utf-8")));
//        try {
//            String ciphertexxt = RsaCryptoUtil.decryptOAEP(ciphertext, merchantPrivateKey);
//            logger.info("rsaDecryptOAEP:"+ciphertexxt);
//            return ciphertexxt;
//        } catch (BadPaddingException e) {
//            e.printStackTrace();
//        }
//        return null;
//    }
//
//    /**
//     * 获取微信平台证书
//     */
//    public String getWechat() throws Exception {
//        // 加载商户私钥（privateKey：私钥字符串）
//        PrivateKey merchantPrivateKey = PemUtil
//                .loadPrivateKey(new ByteArrayInputStream(privateKey.getBytes("utf-8")));
//        //不需要传入微信支付证书了
//        AutoUpdateCertificatesVerifier verifier = new AutoUpdateCertificatesVerifier(
//                new WechatPay2Credentials(mchId, new PrivateKeySigner(mchSerialNo, merchantPrivateKey)),
//                apiV3Key.getBytes("utf-8"));
//
//        WechatPayHttpClientBuilder builder = WechatPayHttpClientBuilder.create()
//                .withMerchant(mchId, mchSerialNo, merchantPrivateKey)
//                .withValidator(new WechatPay2Validator(verifier));
//
//        // 通过WechatPayHttpClientBuilder构造的HttpClient，会自动的处理签名和验签，并进行证书自动更新
//        HttpClient httpClient = builder.build();
//        URIBuilder uriBuilder = new URIBuilder("https://api.mch.weixin.qq.com/v3/certificates");
//        HttpGet httpGet = new HttpGet(uriBuilder.build());
//        httpGet.addHeader("Accept", "application/json");
//        // 后面跟使用Apache HttpClient一样
//        CloseableHttpResponse response = (CloseableHttpResponse) httpClient.execute(httpGet);
//
//        String bodyAsString = EntityUtils.toString(response.getEntity());
//        //String authorization = getToken("GET","https://api.mch.weixin.qq.com/v3/certificates","");
//        // String bodyAsString = com.ly.mpayment.core.util.HttpClient.httpGetWechatUrl("https://api.mch.weixin.qq.com/v3/certificates",authorization);
//        logger.info("微信证书:"+bodyAsString);
//        System.out.println(bodyAsString);
//        //serial_no  5D6EEBAE0EE760A957A691956E86D235206DF50D
//        //expire_time  2026-10-04T11:34:15+08:00
//        //encrypt_certificate {ciphertext:''}
//        return JSON.parseObject(bodyAsString).getJSONArray("data").getJSONObject(0).toString();
//    }
//
//
//    /**
//     *          // Authorization: <schema> <token>
//     *         // GET - getToken("GET", httpurl, "")
//     *         // POST - getToken("POST", httpurl, json)
//     * @param method
//     * @param url
//     * @param body
//     * @return
//     * @throws Exception
//     */
//    private  String getToken(String method, String url, String body) throws Exception {
//        String nonceStr = wxOrderNo();
//        long timestamp = System.currentTimeMillis() / 1000;
//        String message = buildMessage(method, url, timestamp, nonceStr, body);
//        String signature = sign(message.getBytes("utf-8"));
//
//        return "WECHATPAY2-SHA256-RSA2048 mchid=\"" + mchId + "\","
//                + "nonce_str=\"" + nonceStr + "\","
//                + "timestamp=\"" + timestamp + "\","
//                + "serial_no=\"" + mchSerialNo + "\","
//                + "signature=\"" + signature + "\"";
//    }
//
//    /**
//     * 获取私钥。
//     *
//     * @return 私钥对象
//     */
//    public PrivateKey getPrivateKey() throws IOException {
//
//        String content = privateKey;
//        try {
//            String privateKey = content.replace("-----BEGIN PRIVATE KEY-----", "")
//                    .replace("-----END PRIVATE KEY-----", "")
//                    .replaceAll("\\s+", "");
//
//            KeyFactory kf = KeyFactory.getInstance("RSA");
//            return kf.generatePrivate(
//                    new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKey)));
//        } catch (NoSuchAlgorithmException e) {
//            throw new RuntimeException("当前Java环境不支持RSA", e);
//        } catch (InvalidKeySpecException e) {
//            throw new RuntimeException("无效的密钥格式");
//        }
//    }
//
//    private  String sign(byte[] message) throws Exception {
//        Signature sign = Signature.getInstance("SHA256withRSA");
//        PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(
//                new ByteArrayInputStream(privateKey.getBytes("utf-8")));
//        sign.initSign(merchantPrivateKey);
//        sign.update(message);
//
//        return Base64.getEncoder().encodeToString(sign.sign());
//    }
//
//    private  String buildMessage(String method, String url, long timestamp, String nonceStr, String body) throws URISyntaxException {
//        URI uri = URI.create(url);
//        String canonicalUrl = uri.getPath();
//        if (url.indexOf("?") != -1) {
//            canonicalUrl += "?" + uri.getQuery();
//        }
//
//        return method + "\n"
//                + canonicalUrl + "\n"
//                + timestamp + "\n"
//                + nonceStr + "\n"
//                + body + "\n";
//    }
//
//
//    /**
//     * 生成微信支付订单号
//     *
//     * @return
//     */
//    public String wxOrderNo() {
//        // 订单前缀
//        String temp = new DateUtils().toTimeStamp();
//        // 生成15位随机序列
//        String randomSte = getRandomString(15);
//        return temp + randomSte;
//    }
//
//    private  String getRandomString(int length) { // length表示生成字符串的长度
//        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
//        Random random = new Random();
//        StringBuffer sb = new StringBuffer();
//        for (int i = 0; i < length; i++) {
//            int number = random.nextInt(base.length());
//            sb.append(base.charAt(number));
//        }
//        return sb.toString().toUpperCase();
//    }
//    /**
//     * 获取证书。
//     *
//     * @param filename 证书文件路径  (required)
//     * @return X509证书
//     */
//    public  X509Certificate getCertificate(String filename) throws IOException {
//        InputStream fis = new FileInputStream(filename);
//        BufferedInputStream bis = new BufferedInputStream(fis);
//        try {
//            CertificateFactory cf = CertificateFactory.getInstance("X509");
//            X509Certificate cert = (X509Certificate) cf.generateCertificate(bis);
//            cert.checkValidity();
//            return cert;
//        } catch (CertificateExpiredException e) {
//            throw new RuntimeException("证书已过期", e);
//        } catch (CertificateNotYetValidException e) {
//            throw new RuntimeException("证书尚未生效", e);
//        } catch (CertificateException e) {
//            throw new RuntimeException("无效的证书文件", e);
//        } finally {
//            bis.close();
//        }
//    }
//}
